
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using Nitobi;

using Swaf;
using Swaf.BizObj;
using Swaf.Gui;
using Swaf.Gui.AspNet2;

namespace Syrinx.Gui.AspNet.Ajax
{
	public class SyxXmlDataHandler : XmlDataHandler, IDataProvider
	{
		protected BizProcCoordinator m_bpc = null;
		protected System.Web.UI.Page m_page = null;
		protected string m_pageId = null, m_bizProcId = null;
		protected string m_bizRule = null;
		protected object m_bizRuleParam = null;
		protected IBizObjList m_bizobjs = null;
		protected bool m_mustHaveParam = false;

		public SyxXmlDataHandler(System.Web.UI.Page page, string bizRule, object bizRuleParam, bool mustHaveParam)
			: this(page)
		{
			m_bizRule = bizRule;
			m_bizRuleParam = bizRuleParam;
			m_mustHaveParam = mustHaveParam;
		}

		public SyxXmlDataHandler(System.Web.UI.Page page, string bizRule)
			: this(page)
		{
			m_bizRule = bizRule;
		}

		public SyxXmlDataHandler(System.Web.UI.Page page)
		{
			m_page = page;
		}

		protected override IDataProvider getDataProviderForGetRequest(System.Web.HttpRequest request, AjaxGetDataHandlerEventArgs info)
		{
			return this;
		}

		public override void generateCompressedXml(System.IO.TextWriter writer, ColumnsEntity columns, object dataSource, int totalRowCount, AjaxGetDataHandlerEventArgs info)
		{
			string ajaxOutLoc = (string)App.appData.get("AjaxDebugOutput");
			if (dataSource is IBizObjList && !Swaf.Cmn.IsEmpty(ajaxOutLoc))
			{
				string xml = ((IBizObjList)dataSource).Xml;
				File.WriteAllText(Swaf.Cmn.pathCombine(ajaxOutLoc, "Out-" + DateTime.Now.ToString("yyMMddHHmmssF") + ".xml"), xml);
			}
			base.generateCompressedXml(writer, columns, dataSource, totalRowCount, info);
		}

		#region IDataProvider Members

		public string DataId { get { return ""; } }


		public object getDataSource(System.Web.HttpRequest request, AjaxGetDataHandlerEventArgs info)
		{
			m_pageId = request["pi"];
			m_bizProcId = request["bpi"] == null ? null : request["bpi"].Split(',')[0];

			string br = request["br"];
			if (Swaf.Cmn.IsEmpty(br) && !Swaf.Cmn.IsEmpty(m_bizRule))
				br = m_bizRule;
			if (Swaf.Cmn.IsEmpty(m_bizProcId) && Swaf.Cmn.IsEmpty(br))
				br = info.DataSourceId;

			string brParam = null;
			if (br != null)
			{
				Regex r = new Regex(@"(.*?)\[(.*?)\]", RegexOptions.IgnoreCase);
				Match m = r.Match(br);
				IResults rc = null;
				if (m.Success)
				{
					br = m.Groups[1].Value;
					brParam = m.Groups[2].Value;
					if (string.Compare(brParam, "ParentBizProcId", true) == 0)
					{
						ActiveBizProc bizproc = BPC.getActiveBizProc(m_bizProcId);
						brParam = bizproc.OfflineState.Id;
					}
					else if (string.Compare(brParam, "ParentParentBizProcId", true) == 0)
					{
						ActiveBizProc bizproc = BPC.getActiveBizProc(m_bizProcId);
						brParam = bizproc.OfflineState.Id; //m_parentBizProc.ParentBizProc.Parent.Id;
					}
					m_bizobjs = (rc = Swaf.Application.currentApp.ruleMgr.execute(br, brParam)).CallResults as IBizObjList;
				}
				else
				{
					object bizRuleParam = m_bizRuleParam;
					if (!Swaf.Cmn.IsEmpty(info.SearchString))
						bizRuleParam = info.SearchString;
					if (!(m_mustHaveParam && bizRuleParam != null))
					{
						if (bizRuleParam == null)
							m_bizobjs = (rc = Swaf.Application.currentApp.ruleMgr.execute(br)).CallResults as IBizObjList;
						else
							m_bizobjs = (rc = Swaf.Application.currentApp.ruleMgr.execute(br, bizRuleParam)).CallResults as IBizObjList;
					}
				}
			}
			else if (BPC != null)
			{
				ActiveBizProc bizproc = BPC.getActiveBizProc(m_bizProcId);
				if (bizproc != null)
					m_bizobjs = bizproc.BizProc.SourceBizObjs;
			}
			if (m_bizobjs != null && info.StartRecordIndex >= m_bizobjs.numElements)
				m_bizobjs = App.bizObjMgr.createList(m_bizobjs.objectType.Name);

			return m_bizobjs;
		}

		protected override object getRawColumnValueFromDataSourceElement(object rowData, BoundColumn c)
		{
			object val = "";
			try
			{
				if (rowData is IBizObj)
					val = ((IBizObj)rowData).get(c.DataField);
				else if (rowData is IBizObjList)
					val = ((IBizObjList)rowData).get(c.DataField);
				else
					val = base.getRawColumnValueFromDataSourceElement(rowData, c);
			}
			catch (Exception)
			{
				//TODO: Log.
				//We just blow off the exception because if a column is bound to a bad field we wont blow up, just blank data.
			}
			return val;
		}

		public int getTotalDataSize(System.Web.HttpRequest request, AjaxGetDataHandlerEventArgs info)
		{
			if (m_bizobjs == null)
				getDataSource(request, info);
			return (m_bizobjs != null) ? m_bizobjs.numElements : -1;
		}

		public void saveDataFunction(System.Web.HttpRequest request, AjaxSaveDataHandlerEventArgs info)
		{
			throw new NotImplementedException();
		}

		#endregion

		public BizProcCoordinator BPC
		{
			get
			{
				if (m_bpc == null)
				{
					ViewOfflineState pageState = PageStateManager.getState(m_pageId, false);
					if (pageState == null)
						throw new BaseException(string.Format("Invalid page id given for NitobiLiveStreamHandler:{0}:", m_pageId));
					m_bpc = new BizProcCoordinator(m_page, pageState);
				}
				return m_bpc;
			}
			set
			{
				m_bpc = value;
			}
		}
		protected Swaf.IApplication App { get { return Swaf.Application.currentApp; } }

	}
}
